﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
//using AjaxControlToolkit;
using AjaxControlToolkit;
using AresCustomYacht.Code;
using AresCustomYacht.Data;
using AresCustomYacht.DataContract;
using Infragistics.WebUI.UltraWebGrid;
using Infragistics.WebUI.UltraWebListbar;

namespace AresCustomYacht
{
    public partial class Main_Reports : System.Web.UI.Page
    {
        readonly BL _bl = new BL();

        protected void Page_Load(object sender, EventArgs e)
        {

            
            if (Page.IsPostBack) //never reload this page if it is a post back. respond to the events only.
            {
                return; 
                //var trackIdString = Utility.GetQueryStringItem(this, "TrackId");
                //if (!string.IsNullOrEmpty(trackIdString)) return; //TrackId has been selected no need to load this page just get the selected event to fire
            }

            btnAdd.Visible = User.IsInRole("Admin");
            btnEdit.Visible = false; //  User.IsInRole("Admin");

            var boatId = ReadBoatId();
            DisplayAccordion(boatId); //load accordion and append boat id everywhere
            DisplayReportOrReportList(boatId);
        }

        private void DisplayReportOrReportList(int boatId)
        {
//if ReportId is not in the query string then do not show the report grid. just show the list of reports
            var reportId = Utility.GetQueryStringItem(this, "ReportId");

            if (string.IsNullOrEmpty(reportId))
            {
                HideControls();
                return;
            }

            var reportDetailId = Utility.GetQueryStringItem(this, "ReportDetailId");
                //in case the user has selected a report those two fields will not be empty
            if (string.IsNullOrEmpty(reportDetailId) || reportDetailId == "0") //display listbox of reports
            {
                DisplayReportList();
            }
            else //Display the report detail itself in the ultrawebgrid
            {
                DisplayTracking(reportDetailId, boatId);
            }
        }

        private int ReadBoatId()
        {
            int boatId;
            if (User.IsInRole("Admin")) //User is admin and he must have selected a boat already
            {
                boatId = int.Parse(Utility.GetQueryStringItem(this, "BoatId")); // goat coming from boats.aspx
            }
            else
            {
                boatId = _bl.GetBoat((Guid) Membership.GetUser().ProviderUserKey).BoatId; //if a user load the default boat
            }
            return boatId;
        }

        private void DisplayTracking(string reportDetailId, int boatId)
        {
            grdTracking.Visible = true;
            lblReportDetail.Visible = false;
            DisplayReport(boatId, Convert.ToInt32(reportDetailId));
        }

        private void DisplayReportList()
        {
            grdTracking.Visible = false;
            lblReportDetail.Visible = true;

            DisplayReportList(Convert.ToInt32(Utility.GetQueryStringItem(this, "ReportId")));
        }

        private void HideControls()
        {
            grdTracking.Visible = false;
            lblReportDetail.Visible = false; 
            btnAdd.Visible = false;
            btnEdit.Visible = false;
        }

        private void DisplayReportList(int reportId) //show specific report
        {

                var detailedReports = ((List<ReportDetail>)Application["ReportDetails"]).Where(p => p.ReportId == reportId).ToList();

                
                var reportDetails = new StringBuilder();
                
                detailedReports.ForEach(p=>
                                            {
                                                var linkAddress = "Main-Reports.aspx?k=" + Utility.Encrypt("ReportId=" + p.ReportId + "&BoatId=" +  Utility.GetQueryStringItem(this,"BoatId") + "&ReportDetailId=" + p.ReportDetailId );
                                                var linkAddressPDF = "Main-Reports.aspx?k=" + Utility.Encrypt("ReportId=" + p.ReportId + "&BoatId=" + Utility.GetQueryStringItem(this, "BoatId") + "&ReportDetailId=" + p.ReportDetailId +"&Format=PDF");
                                                var linkAddressXLS = "Main-Reports.aspx?k=" + Utility.Encrypt("ReportId=" + p.ReportId + "&BoatId=" + Utility.GetQueryStringItem(this, "BoatId") + "&ReportDetailId=" + p.ReportDetailId + "&Format=XLS");

                                                if (p.IsReport == null || !Convert.ToBoolean(p.IsReport)) //not a report
                                                {
                                                    reportDetails.AppendFormat("{0} <br/> -------------------------------------------------- <br/>",p.Name);
                                                }
                                                else
                                                {
                                                    reportDetails.AppendFormat("<a href=\"{0}\"> {1} </a>  [<a href=\"{2}\"> PDF </a>]  <br/>", linkAddress,
                                                        p.Name, linkAddressPDF);
                                                }


                                            });

                lblReportDetail.Text = reportDetails.ToString();


            
        }

        private void DisplayReport(int boatId, int reportDetailId)
        {

                //get the userBoat
                //TODO: User can have more than one boat

                var boat = _bl.GetBoat(boatId);
                var reportDetail = ((List<ReportDetail>)Application["ReportDetails"]).First(p => p.ReportDetailId == reportDetailId);
                lblReportName.Text = reportDetail.Name + "  [" + boat.BoatName  + "]";

                switch (reportDetail.ReportCode)
                {
                    case "CSTSUM":
                        grdTracking.DataSource = _bl.GetCostSummaryReport(reportDetailId, boat.BoatId, reportDetail.Parameters);
                        grdTracking.DataBind();
                        
                        HilightTotals();
                        break;

                    case "CSTDETTRA": //Cost details by Trade
                        grdTracking.DataSource = _bl.GetCostDetailByTrade(reportDetailId, boat.BoatId, reportDetail.Parameters);
                        grdTracking.DataBind();
                        HilightTotals();
                        break;

                    case "CSTDETLOC": //Cost details by location
                        grdTracking.DataSource = _bl.GetCostDetailByLocation(reportDetailId, boat.BoatId, reportDetail.Parameters);
                        grdTracking.DataBind();
                        HilightTotals();
                        break;

                    default:
                        lblReportName.Text = "Report not defined" + " " + reportDetail.ReportCode ;
                        break;
                }

            var format = Utility.GetQueryStringItem(this, "Format");
            if (!string.IsNullOrEmpty(format) && format == "PDF")
                ExportToPdf();

            if (!string.IsNullOrEmpty(format) && format == "XLS")
                ExportToXls();
        }

        private void DisplayAccordion(int boatId)
        {
                var reports = (List<Report>)Application["Reports"];
                var divisions = reports.Select(p => p.Category).Distinct().ToList();

                foreach (var division in divisions)
                {
                    var cat = division;
                    var lbTitle = new Label();
                    var lbContent = new Label();
                    lbTitle.Text = division;
                    var pn = new AccordionPane {ID = division, Visible = true };
                    pn.HeaderContainer.Controls.Add(lbTitle);
                    

                    var categoryReports = reports.Where(p => p.Category == cat).ToList();

                    var reportsString = new StringBuilder();
                    reportsString.Append( "<div runat=\"server\"  class=\"accordionContent\" ID=" + division.Replace(" ", "") + ">");
                    categoryReports.ForEach(p =>
                    {
                        var linkAddress = "Main-Reports.aspx?k=" + Utility.Encrypt("ReportId=" + p.ReportId + "&BoatId=" + boatId + "&ReportDetailId=0");
                        if (p.IsReport == null || !Convert.ToBoolean(p.IsReport)) //not a report
                        {
                            reportsString.AppendFormat("{0} <br/>", p.Name);
                        }
                        else
                        {
                            reportsString.AppendFormat("<a href=\"{0}\"> {1} </a> <br/>", linkAddress,
                                p.Name);
                        }


                    });


                    reportsString.Append("</div>");
                    lbContent.Text = reportsString.ToString();
                    pn.ContentContainer.Controls.Add(lbContent);
                    MyAccordion.Panes.Add(pn);

                }
                
                
            

            //MyAccordion.SelectedIndex = 0;
        }

        private void HilightTotals()
        {

            foreach (var row in grdTracking.Rows)
            {
                
            }


        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var boatId = int.Parse(Utility.GetQueryStringItem(this, "BoatId"));
            var linkAddress = Utility.Encrypt("Mode=0&BoatId=" + boatId);
            Response.Redirect("P-Division.aspx?k=" + linkAddress);
        }

        protected void grdReport_InitializeLayout(object sender, Infragistics.WebUI.UltraWebGrid.LayoutEventArgs e)
        {


            /* Move default column headers to the header row */
            HilightTotals();
   
        }



        protected void btnEdit_Click(object sender, EventArgs e)
        {


        }


        protected void Button1_Click(object sender, EventArgs e)
        {
            //Response.Clear();
            //Response.Buffer = true;
            //Response.ContentType = "application/vnd.ms-excel";
            //Response.AddHeader("content-disposition", "attachment;filename=YourFiles.xls");
            //Response.Charset = "";
            //this.EnableViewState = false;

            //var sr = new System.IO.StringWriter();
            //var htw = new System.Web.UI.HtmlTextWriter(sr);

            ////grdReport.RenderControl(htw);

            //Response.Write(sr.ToString());
            //Response.End();
        }

        protected void Button1_Click1(object sender, EventArgs e)
        {


        }

        protected void ExportToPdf()
        {
            var grd = new UltraWebGrid { DataSource = grdTracking.DataSource };
            grd.DataBind();
            UltraWebGridDocumentExporter1.DownloadName = lblReportName.Text.Replace(" ", "");
            grd.GridLines = UltraGridLines.Both;
           

            foreach(UltraGridColumn c in grd.Columns)
            {
                c.Format = "###,###0.00";
            }
            UltraWebGridDocumentExporter1.Export(grd);
        }

        protected void ExportToXls()
        {
            var grd = new UltraWebGrid { DataSource = grdTracking.DataSource };
            grd.DataBind();
            UltraWebGridExcelExporter1.Export(grd);
        }

        protected void ltnMaximize_Click(object sender, EventArgs e)
        {
            if (ltnMaximize.Text == "Maximize")
            {
                MyAccordion.Visible = false;
                ltnMaximize.Text = "Restore";
            }
            else
            {
                MyAccordion.Visible = true;
                ltnMaximize.Text = "Maximize";
                DisplayAccordion(ReadBoatId());
            }
        }

        protected void grdTracking_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                var headerGridRow = new GridViewRow(0, 0, DataControlRowType.Header,DataControlRowState.Insert);
                
                var headerCell = new TableCell {Text = "", ColumnSpan = 2};
                headerGridRow.Cells.Add(headerCell);


                headerCell = new TableCell {Text = "Budget", ColumnSpan = 4, HorizontalAlign = HorizontalAlign.Center};
                headerGridRow.Cells.Add(headerCell);

                headerCell = new TableCell {Text = "Actual", ColumnSpan = 5, HorizontalAlign = HorizontalAlign.Center};
                headerGridRow.Cells.Add(headerCell);

                headerCell = new TableCell
                                 {Text = "Remaining", ColumnSpan = 4, HorizontalAlign = HorizontalAlign.Center};
                headerGridRow.Cells.Add(headerCell);

                grdTracking.Controls[0].Controls.AddAt(0, headerGridRow);

            }
        }

        protected void grdTracking_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var dataItem = ((Summary) e.Row.DataItem);
                e.Row.CssClass = dataItem.cssClass;
                var ltn = (LinkButton) e.Row.Cells[0].FindControl("ltnCode");
                var boatId = int.Parse(Utility.GetQueryStringItem(this, "BoatId"));
                if (dataItem.TrackId != 0) ltn.Text = dataItem.Code;
                
                if (User.IsInRole("Admin"))
                    ltn.OnClientClick = "window.open('Track.aspx?k=" + Utility.Encrypt("Mode=1&BoatId=" + boatId + "&TrackId=" + dataItem.TrackId) + "');";

            }
        }
    }
}